package com.vision.util.http.exception;

import com.alibaba.fastjson.JSON;
import com.vision.util.http.util.HttpRequestUtil;
import com.vision.util.bean.ReturnMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CommonExceptionResolver implements HandlerExceptionResolver {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 出现异常展示页面
     */
    private String errorPath;

    public CommonExceptionResolver(String errorPath) {
        if (StringUtils.isEmpty(errorPath)) {
            throw new IllegalArgumentException("errorPath can not be null, please add a handler of url when the request appeared exception ");
        }
        this.errorPath = errorPath;
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        logger.error("request " + httpServletRequest.getRequestURL() + "exception->{}" + e.getMessage());
        httpServletResponse.setCharacterEncoding("UTF-8");
        boolean ajax = HttpRequestUtil.isAjax(httpServletRequest);
        if (ajax) {
            try {
                ReturnMsg returnMsg = new ReturnMsg();
                returnMsg.setSuccess(false);
                returnMsg.setMessage("系统繁忙");
                httpServletResponse.getWriter().print(JSON.toJSONString(returnMsg));
            } catch (Exception e2) {
                logger.error("出现错误->{}" + e2.getMessage());
            }
        }
        return new ModelAndView(errorPath);
//        modelAndView.setv

    }
}
